import type { App, Directive, DirectiveBinding } from 'vue'
import { useUserStore } from '@/stores/user'

// 权限指令类型
interface PermissionDirectiveBinding extends DirectiveBinding {
  value: string | string[] | {
    permission?: string | string[]
    role?: string | string[]
    action?: 'show' | 'hide' | 'disable'
  }
}

// 检查权限
function checkPermission(value: any): boolean {
  const userStore = useUserStore()
  
  if (!value) {
    return true
  }
  
  // 超级管理员拥有所有权限
  if (userStore.isSuperAdmin) {
    return true
  }
  
  // 处理不同的值类型
  if (typeof value === 'string') {
    // 单个权限字符串
    return userStore.hasPermission(value)
  } else if (Array.isArray(value)) {
    // 权限数组，需要拥有任一权限
    return userStore.hasAnyPermission(value)
  } else if (typeof value === 'object') {
    // 对象形式，可同时检查权限和角色
    const { permission, role } = value
    
    let hasPermission = true
    let hasRole = true
    
    if (permission) {
      if (Array.isArray(permission)) {
        hasPermission = userStore.hasAnyPermission(permission)
      } else {
        hasPermission = userStore.hasPermission(permission)
      }
    }
    
    if (role) {
      if (Array.isArray(role)) {
        hasRole = role.some((r: string) => userStore.hasRole(r))
      } else {
        hasRole = userStore.hasRole(role)
      }
    }
    
    return hasPermission && hasRole
  }
  
  return false
}

// 处理元素显示/隐藏
function handleElement(el: HTMLElement, binding: PermissionDirectiveBinding): void {
  const hasPermission = checkPermission(binding.value)
  
  // 获取操作类型
  let action = 'hide'
  if (typeof binding.value === 'object' && binding.value.action) {
    action = binding.value.action
  }
  
  if (!hasPermission) {
    switch (action) {
      case 'hide':
        el.style.display = 'none'
        break
      case 'disable':
        if (el.tagName === 'BUTTON' || el.tagName === 'INPUT') {
          (el as HTMLButtonElement | HTMLInputElement).disabled = true
          el.classList.add('is-disabled')
        } else {
          el.style.pointerEvents = 'none'
          el.style.opacity = '0.5'
          el.classList.add('is-disabled')
        }
        break
      case 'show':
        // 反向逻辑，没有权限时显示
        el.style.display = 'block'
        break
    }
  } else {
    // 有权限时的处理
    switch (action) {
      case 'hide':
        el.style.display = ''
        break
      case 'disable':
        if (el.tagName === 'BUTTON' || el.tagName === 'INPUT') {
          (el as HTMLButtonElement | HTMLInputElement).disabled = false
          el.classList.remove('is-disabled')
        } else {
          el.style.pointerEvents = ''
          el.style.opacity = ''
          el.classList.remove('is-disabled')
        }
        break
      case 'show':
        el.style.display = 'none'
        break
    }
  }
}

// v-permission 权限指令
export const permission: Directive = {
  mounted(el: HTMLElement, binding: PermissionDirectiveBinding) {
    handleElement(el, binding)
  },
  updated(el: HTMLElement, binding: PermissionDirectiveBinding) {
    handleElement(el, binding)
  }
}

// v-role 角色指令
export const role: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const userStore = useUserStore()
    const roles = binding.value
    
    if (!roles) {
      return
    }
    
    let hasRole = false
    if (Array.isArray(roles)) {
      hasRole = roles.some((role: string) => userStore.hasRole(role))
    } else {
      hasRole = userStore.hasRole(roles)
    }
    
    if (!hasRole) {
      el.style.display = 'none'
    }
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    const userStore = useUserStore()
    const roles = binding.value
    
    if (!roles) {
      return
    }
    
    let hasRole = false
    if (Array.isArray(roles)) {
      hasRole = roles.some((role: string) => userStore.hasRole(role))
    } else {
      hasRole = userStore.hasRole(roles)
    }
    
    if (!hasRole) {
      el.style.display = 'none'
    } else {
      el.style.display = ''
    }
  }
}

// v-auth 综合权限指令
export const auth: Directive = {
  mounted(el: HTMLElement, binding: PermissionDirectiveBinding) {
    handleElement(el, binding)
  },
  updated(el: HTMLElement, binding: PermissionDirectiveBinding) {
    handleElement(el, binding)
  }
}

// v-permission-all 需要拥有所有权限
export const permissionAll: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const userStore = useUserStore()
    const permissions = binding.value
    
    if (!permissions || !Array.isArray(permissions)) {
      return
    }
    
    const hasAllPermissions = userStore.hasAllPermissions(permissions)
    
    if (!hasAllPermissions) {
      el.style.display = 'none'
    }
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    const userStore = useUserStore()
    const permissions = binding.value
    
    if (!permissions || !Array.isArray(permissions)) {
      return
    }
    
    const hasAllPermissions = userStore.hasAllPermissions(permissions)
    
    if (!hasAllPermissions) {
      el.style.display = 'none'
    } else {
      el.style.display = ''
    }
  }
}

// 权限检查工具函数
export function hasPermission(permission: string | string[]): boolean {
  const userStore = useUserStore()
  
  if (Array.isArray(permission)) {
    return userStore.hasAnyPermission(permission)
  } else {
    return userStore.hasPermission(permission)
  }
}

export function hasRole(role: string | string[]): boolean {
  const userStore = useUserStore()
  
  if (Array.isArray(role)) {
    return role.some(r => userStore.hasRole(r))
  } else {
    return userStore.hasRole(role)
  }
}

export function hasAuth(value: any): boolean {
  return checkPermission(value)
}

// 安装权限指令
export function setupDirectives(app: App): void {
  app.directive('permission', permission)
  app.directive('role', role)
  app.directive('auth', auth)
  app.directive('permission-all', permissionAll)
}

// 指令使用示例：
/*
<!-- 单个权限 -->
<el-button v-permission="'user:create'">新增用户</el-button>

<!-- 多个权限（任一） -->
<el-button v-permission="['user:create', 'user:update']">操作</el-button>

<!-- 角色权限 -->
<el-button v-role="'ADMIN'">管理员操作</el-button>
<el-button v-role="['ADMIN', 'SUPER_ADMIN']">高级操作</el-button>

<!-- 综合权限 -->
<el-button v-auth="{ permission: 'user:delete', role: 'ADMIN' }">删除用户</el-button>

<!-- 禁用而不是隐藏 -->
<el-button v-auth="{ permission: 'user:edit', action: 'disable' }">编辑</el-button>

<!-- 需要所有权限 -->
<el-button v-permission-all="['user:create', 'user:update', 'user:delete']">完全操作</el-button>
*/
